package com.qizhan100.qtools.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

import com.qizhan100.qtools.common.StringUtils;

public class FileUtil {
    protected static Logger logger = Logger.getLogger(FileUtil.class);
    
    /**
     * 读取txt文件的内容
     * 
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file) {
        String result = "";
        try {
            BufferedReader br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
                result = result + "\n" + s;
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    public static double getDirMSize(File file) {
        // 判断文件是否存在
        if (file.exists()) {
            // 如果是目录则递归计算其内容的总大小
            if (file.isDirectory()) {
                File[] children = file.listFiles();
                double size = 0;
                for (File f : children)
                    size += getDirMSize(f);
                return size;
            } else {// 如果是文件则直接返回其大小,以“兆”为单位
                double size = (double) file.length() / 1024 / 1024;
                return size;
            }
        } else {
            logger.error(file.getAbsolutePath() + "文件或者文件夹不存在，请检查路径是否正确！");
            return 0.0;
        }
    }
    
    public static void writeFile(String path, String filename, String context,
        boolean append) {
        FileWriter fw = null;
        try {
            if (StringUtils.isNotBlank(path) && StringUtils.isNotBlank(filename) && context != null) {
                File p = new File(path);
                if (!p.exists()) {
                    p.mkdirs();
                }
                File file = new File(path + File.separator + filename);
                if (!file.exists()) {
                    file.createNewFile();
                }
                fw = new FileWriter(file, append);
                fw.write(context);
                fw.flush();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
}
